package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    @Override
    public List<User> findAll() {
        List<User> users=new ArrayList<>();
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc", "root", "072417");
            //3.编写sql语句
            String sql = "select * from demo";
            //4.预处理sql var.
            preparedStatement = conn.prepareStatement(sql);
            //5.如果有参数，设置参数
            //6.执行sql
            resultSet = preparedStatement.executeQuery();
            //7.如果是查询就遍历结果，如果是增删改查 判断是否成功
            while (resultSet.next()) {
                User u=new User();
                u.setId(resultSet.getInt(1));
                u.setName(resultSet.getString(2));
                u.setPass(resultSet.getString(3));
                users.add(u);
            }
            return users;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //8.关闭资源
            try {
                if (preparedStatement != null)
                    preparedStatement.close();
                if (resultSet != null)
                    resultSet.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
